/**
 * RemoteServiceHeartbeater.java
 */
package fss.remote.util;

import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.logging.Logger;

import fss.common.communication.PingRequest;
import fss.core.FssThrowable;
import fss.remote.ServiceRegistry;
import fss.util.rmi.RmiId;
import fss.util.rmi.RmiUtils;

/**
 * Heartbeater that pings Remote Service(s) registered with a Remote Registry.
 * 
 * @author thinh
 *
 */
public class RemoteServiceHeartbeater extends Thread implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * The logger.
     */
    private static transient final Logger logger = Logger.getLogger(RemoteServiceHeartbeater.class.getName());
    /**
     * A reference to the service registry.
     */
    private ServiceRegistry registry = null;
    /**
     * Heartbeat interval (milliseconds).
     */
    private int interval = 0;
    /**
     * Constructs a heartbeater for the specified service identifier that will 
     * heartbeat the specified service registry.
     * @param id the service id.
     * @param poll the poll time in seconds
     */
    public RemoteServiceHeartbeater(RmiId id, int poll) {
        super(id.toString());
        this.interval = poll * 1000;
        registry = (ServiceRegistry) RmiUtils.getRemoteObject(id);
        if(registry == null) {
            throw new FssThrowable("Cannot obtain instances of ServiceRegistry (" + id + ")");
        }
    }
    @Override
    public void run() {
        logger.info("RemoteServiceHeartbeater started: " + getName());
        while(true) {
            try {
                sleep(interval);
                try {
                    if(registry.getRegisteredServiceList().size() != 0) {
                        PingRequest ping = new PingRequest(registry.getId());
                        registry.processRequest(ping);
                    }
                } catch (RemoteException e) {
                    logger.warning("Thread RemoteServiceHeartbeater caught exception: " + e);
                }
            } catch (InterruptedException e) {
                logger.info("Thread RemoteServiceHeartbeater interrupted.");
            }
        }
    }
}
